package com.seari.custody.service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.seari.custody.bean.Meeting;
import com.seari.custody.bean.Message;
import com.seari.custody.bean.MessageExample;
import com.seari.custody.mapper.MessageMapper;
import com.seari.custody.service.MeetingService;
import com.seari.custody.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private MeetingService meetingService;


    /**
     * 用户id获取未读消息
     *
     * @param userNumber
     * @return
     */
    @Override
    public List<Message> statisticsUnReadMessageByUserNumber(String userNumber) {
        MessageExample messageExample = new MessageExample();
        //接收者 未读 会议类型的消息
        messageExample.createCriteria().andRecvUserIdEqualTo(userNumber).andReadTimeEqualTo(0);
        messageExample.setOrderByClause("create_time DESC");

        List<Message> messages = messageMapper.selectByExample(messageExample);
        //过了会议开始时间就不通知了

        Iterator<Message> iterator = messages.iterator();
        while (iterator.hasNext()) {
            Message message = iterator.next();
            Meeting meeting = meetingService.qryOne(message.getAssociatedId());
            int compare = meeting.getStartTime().compareTo(new Date());
            if (compare < 0) {
                message.setReadTime(1);
                updateMessage(message);
                iterator.remove();
            }
        }
        return messages;
    }

    @Override
    public Integer saveMessage(Message message) {
        message.setId(IdUtil.objectId());
        int i = messageMapper.insertSelective(message);
        return i;
    }

    @Override
    public Integer updateMessage(Message message) {
        return messageMapper.updateByPrimaryKeySelective(message);
    }

    @Override
    public Message getById(String id) {
        return messageMapper.selectByPrimaryKey(id);
    }

    @Override
    public String qryMessageBySendIdAndReceiveId(String sendId, String receiveId) {
        MessageExample messageExample = new MessageExample();
        messageExample.createCriteria().andRecvUserIdEqualTo(receiveId).andSendUserIdEqualTo(sendId);
        List<Message> messages = messageMapper.selectByExample(messageExample);
        if (CollectionUtil.isNotEmpty(messages)) {
            return messages.get(0).getContent();
        }
        return "";
    }
}
